<?php
declare(strict_types=1);
ob_start(); // 开启输出缓冲
register_shutdown_function(function() {
    // 确保只输出JSON
    if (headers_sent() && strpos(ob_get_contents(), '<') !== false) {
        ob_clean();
        http_response_code(500);
        die(json_encode(['status' => 'error', 'message' => '系统内部错误']));
    }
});

/*--------------------------------------------------
| 会话安全配置（必须在session_start之前设置）
|-------------------------------------------------*/
ini_set('session.cookie_httponly', '1');
ini_set('session.use_strict_mode', '1');
ini_set('session.cookie_samesite', 'Lax');
session_start();

/*--------------------------------------------------
| 用户认证检查
|-------------------------------------------------*/
if (!isset($_SESSION['username'])) {
    header('Location: login.php');
    exit();
}

/*--------------------------------------------------
| 系统常量配置
|-------------------------------------------------*/
define('MAX_FILE_SIZE', 5 * 1024 * 1024 * 1024); // 5GB
define('UPLOAD_DIR', __DIR__.'/upload/userfile/');
define('CONFIG_FILE', UPLOAD_DIR.'files.json');
define('LOG_FILE', __DIR__.'/file_system.log');

/*--------------------------------------------------
| 初始化文件系统 - 确保所有目录和文件自动创建
|-------------------------------------------------*/
try {
    // 确保上传目录存在
    if (!file_exists(UPLOAD_DIR)) {
        mkdir(UPLOAD_DIR, 0755, true);
    }
    
    // 确保目录中有index.html文件
    if (!file_exists(UPLOAD_DIR.'index.html')) {
        file_put_contents(UPLOAD_DIR.'index.html', '');
    }
    
    // 确保配置文件存在
    if (!file_exists(CONFIG_FILE)) {
        file_put_contents(CONFIG_FILE, json_encode([]));
    }
    
    // 确保日志文件存在
    if (!file_exists(LOG_FILE)) {
        file_put_contents(LOG_FILE, '');
    }
    
    $db = FileDB::getInstance($_SESSION['username'] ?? 'system');
    $db->cleanExpired();
} catch (Exception $e) {
    error_log("[".date('Y-m-d H:i:s')."] 系统初始化失败: ".$e->getMessage());
    die(json_encode(['status' => 'error', 'message' => '系统初始化失败']));
}

/*--------------------------------------------------
| 数据库操作类
|-------------------------------------------------*/
class FileDB {
    private static $instance = null;
    private $data = [];
    private $currentUser;

    private function __construct(string $username) {
        $this->currentUser = $username;
        $this->loadData();
    }

    public static function getInstance(string $username): self {
        if (!self::$instance) {
            self::$instance = new self($username);
        }
        return self::$instance;
    }

    private function loadData(): void {
        if (file_exists(CONFIG_FILE)) {
            $this->data = json_decode(file_get_contents(CONFIG_FILE), true) ?: [];
        }
    }

    public function addFile(array $fileInfo): string {
        foreach ($this->data as $file) {
            if ($file['user'] === $this->currentUser 
                && $file['name'] === $fileInfo['name']
                && $file['extension'] === ($fileInfo['extension'] ?? '')) {
                throw new RuntimeException("文件名已存在");
            }
        }
        
        $userFiles = $this->getUserFiles();
        if (count($userFiles) >= 5) {
            throw new RuntimeException("最多只能上传5个文件");
        }
        
        $fileId = $this->generateFileId();
        $this->data[$fileId] = [
            'id' => $fileId,
            'name' => $fileInfo['name'],
            'extension' => $fileInfo['extension'] ?? '',
            'size' => $fileInfo['size'],
            'user' => $this->currentUser,
            'upload_time' => time(),
            'expire_time' => time() + 86400,
            'type' => $fileInfo['type']
        ];
        $this->save();
        return $fileId;
    }

    public function searchFile(string $fileId): array {
        if (!isset($this->data[$fileId])) {
            throw new RuntimeException("文件不存在");
        }
        return $this->data[$fileId];
    }
    
    public function getUserFiles(): array {
        return array_filter($this->data, function($file) {
            return $file['user'] === $this->currentUser && $file['expire_time'] > time();
        });
    }

    private function generateFileId(): string {
        $attempt = 0;
        do {
            $id = substr(str_shuffle(hash('sha256', uniqid((string)mt_rand(), true))), 0, 6);
            if (!isset($this->data[$id])) return $id;
        } while ($attempt++ < 10);
        throw new RuntimeException("无法生成唯一文件ID");
    }

    private function save(): void {
        $tempFile = tempnam(UPLOAD_DIR, 'tmp');
        file_put_contents($tempFile, json_encode($this->data, JSON_PRETTY_PRINT));
        rename($tempFile, CONFIG_FILE);
    }
    
    public function cleanExpired(): void {
        foreach ($this->data as $id => $file) {
            if ($file['expire_time'] < time()) {
                unset($this->data[$id]);
                @unlink(UPLOAD_DIR . $id);
            }
        }
        $this->save();
    }
}

/*--------------------------------------------------
| 请求处理器
|-------------------------------------------------*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 解析JSON格式请求
    if (isset($_SERVER['CONTENT_TYPE']) && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
        $jsonInput = file_get_contents('php://input');
        $jsonData = json_decode($jsonInput, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            $_POST = array_merge($_POST, $jsonData);
        }
    }
    
    header('Content-Type: application/json');
    $response = ['status' => 'error'];
    
    try {
        $currentUser = $_SESSION['username'];
        $db = FileDB::getInstance($currentUser);
        $action = $_POST['action'] ?? '';

        switch ($action) {
            case 'upload':
                try {
                    // 获取原始文件名
                    $originalName = $_FILES['file']['name'];
                    
                    $fileId = $db->addFile([
                        'name' => pathinfo($originalName, PATHINFO_FILENAME),
                        'extension' => pathinfo($originalName, PATHINFO_EXTENSION),
                        'size' => $_FILES['file']['size'],
                        'type' => mime_content_type($_FILES['file']['tmp_name'])
                    ]);

                    // 移动文件（使用绝对路径）
                    $destination = UPLOAD_DIR . $fileId;
                    if (!move_uploaded_file($_FILES['file']['tmp_name'], $destination)) {
                        throw new RuntimeException("无法保存文件");
                    }

                    $response = [
                        'status' => 'success',
                        'data' => [
                            'id' => $fileId,
                            'name' => htmlspecialchars($_POST['name'] ?? pathinfo($originalName, PATHINFO_FILENAME)),
                            'extension' => pathinfo($originalName, PATHINFO_EXTENSION),
                            'expire' => date('Y-m-d H:i', time() + 86400)
                        ]
                    ];
                } catch (Exception $e) {
                    http_response_code(400);
                    die(json_encode(['status' => 'error', 'message' => $e->getMessage()]));
                }
                break;
                
            case 'search':
                $fileId = substr(preg_replace('/[^a-f0-9]/i', '', $_POST['id'] ?? ''), 0, 6);
                
                try {
                    $file = $db->searchFile($fileId);
                    $response = [
                        'status' => 'success',
                        'data' => [
                            'id' => $fileId,
                            'name' => $file['name'],
                            'size' => $file['size'],
                            'expire' => date('Y-m-d H:i', $file['expire_time'])
                        ]
                    ];
                } catch (Exception $e) {
                    // 如果数据库信息不存在，只返回文件ID
                    $response = [
                        'status' => 'success',
                        'data' => [
                            'id' => $fileId,
                            'name' => '未知文件',
                            'size' => filesize(UPLOAD_DIR.$fileId),
                            'expire' => '未知'
                        ]
                    ];
                }
                break;

            case 'myfiles':
                $files = $db->getUserFiles();
                $response = [
                    'status' => 'success',
                    'data' => array_values(array_map(function($file) {
                        return [
                            'id' => $file['id'],
                            'name' => $file['name'],
                            'size' => $file['size'],
                            'upload_time' => date('Y-m-d H:i', $file['upload_time'])
                        ];
                    }, $files))
                ];
                break;

            case 'download':
                $fileId = substr(preg_replace('/[^a-f0-9]/i', '', $_POST['id'] ?? ''), 0, 6);
                
                // 直接下载文件，不检查用户权限
                $filePath = UPLOAD_DIR.$fileId;
                
                if (!file_exists($filePath)) {
                    throw new RuntimeException("文件不存在");
                }
                
                // 尝试从数据库获取文件名（如果存在）
                try {
                    $fileInfo = $db->searchFile($fileId);
                    $filename = $fileInfo['name'];
                    if (!empty($fileInfo['extension'])) {
                        $filename .= '.' . $fileInfo['extension'];
                    }
                } catch (Exception $e) {
                    // 如果数据库信息不存在，使用默认文件名
                    $filename = 'download_'.$fileId;
                }
                
                // 修复文件格式问题 - 设置正确的Content-Type
                $contentType = mime_content_type($filePath);
                if (!$contentType) {
                    $contentType = 'application/octet-stream';
                }
                
                header('Content-Type: ' . $contentType);
                header('Content-Disposition: attachment; filename="'.$filename.'"');
                header('Content-Length: ' . filesize($filePath));
                readfile($filePath);
                exit;

            default:
                throw new RuntimeException("无效操作");
        }
    } catch (Exception $e) {
        $response['message'] = $e->getMessage();
        error_log("[".date('Y-m-d H:i:s')."] 操作失败: ".$e->getMessage());
    }
    
    exit(json_encode($response));
}

/*--------------------------------------------------
| 前端界面（采用白色主题和黑色按钮风格）
|-------------------------------------------------*/
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JIIL文件管理系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        /* ================= 全局样式 ================= */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
            min-height: 100vh;
        }
        
        /* ================= 白色顶部栏 ================= */
        .top-bar {
            background: white;
            padding: 16px 20px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            display: flex;
            align-items: center;
            position: sticky;
            top: 0;
            width: 100%;
            z-index: 1000;
        }
        
        .back-btn {
            background: none;
            border: none;
            color: #000;
            font-size: 20px;
            margin-right: 15px;
            cursor: pointer;
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.3s ease;
        }
        
        .back-btn:hover {
            background: #f0f2f5;
        }
        
        .page-title {
            font-size: 20px;
            font-weight: 600;
            color: #333;
            flex-grow: 1;
            text-align: center;
        }
        
        /* ================= 主容器 ================= */
        .container {
            max-width: 1000px;
            margin: 80px auto 30px;
            padding: 0 20px;
        }
        
        /* ================= 主按钮区域 ================= */
        .main-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 25px;
            margin-bottom: 40px;
        }

        .big-button {
            width: 100%;
            padding: 22px;
            background: #000;
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 12px;
        }

        .big-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
            background: #222;
        }
        
        .big-button i {
            font-size: 24px;
        }

        /* ================= 底部退出按钮 ================= */
        .footer {
            position: fixed;
            bottom: 30px;
            width: 100%;
            text-align: center;
        }

        .logout-btn {
            padding: 14px 45px;
            background: #000;
            color: white;
            border: none;
            border-radius: 30px;
            cursor: pointer;
            font-weight: 600;
            font-size: 16px;
            transition: all 0.3s ease;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
        }

        .logout-btn:hover {
            background: #222;
            transform: translateY(-2px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
        }

        /* ================= 弹窗系统 ================= */
        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            align-items: center;
            justify-content: center;
            z-index: 999;
        }

        .modal-content {
            background: white;
            padding: 30px;
            border-radius: 16px;
            width: 90%;
            max-width: 600px;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            position: relative;
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }
        
        .modal-title {
            font-size: 24px;
            font-weight: 700;
            color: #333;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 28px;
            cursor: pointer;
            color: #666;
            transition: all 0.3s ease;
        }
        
        .close-btn:hover {
            color: #000;
            transform: scale(1.1);
        }
        
        /* ================= 表单样式 ================= */
        .form-group {
            margin-bottom: 20px;
        }
        
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #444;
        }
        
        .form-input {
            width: 100%;
            padding: 16px;
            border: 1px solid #ddd;
            border-radius: 10px;
            font-size: 16px;
            transition: all 0.3s ease;
        }
        
        .form-input:focus {
            border-color: #3b82f6;
            outline: none;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.15);
        }
        
        .progress-bar {
            height: 15px;
            background: #eee;
            border-radius: 8px;
            overflow: hidden;
            margin: 20px 0;
        }

        .progress-fill {
            width: 0%;
            height: 100%;
            background: #000;
            transition: width 0.3s ease;
        }
        
        .btn-group {
            display: flex;
            gap: 15px;
            margin-top: 25px;
        }
        
        .btn {
            flex: 1;
            padding: 16px;
            border-radius: 10px;
            font-weight: 600;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            border: none;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        
        .btn-primary {
            background: #000;
            color: white;
        }
        
        .btn-primary:hover {
            background: #222;
            transform: translateY(-2px);
        }
        
        .btn-secondary {
            background: #f5f5f5;
            color: #333;
        }
        
        .btn-secondary:hover {
            background: #e5e7eb;
            transform: translateY(-2px);
        }
        
        /* ================= 文件列表 ================= */
        .file-list-container {
            overflow-y: auto;
            max-height: calc(70vh - 100px);
            padding: 10px;
            border: 1px solid #eee;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .file-item {
            padding: 15px;
            border-bottom: 1px solid #f0f0f0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .file-item:hover {
            background: #f9f9f9;
        }
        
        .file-info {
            flex: 1;
        }
        
        .file-name {
            font-weight: 600;
            margin-bottom: 5px;
            color: #333;
        }
        
        .file-meta {
            font-size: 14px;
            color: #666;
        }
        
        .file-id {
            font-family: monospace;
            background: #f0f0f0;
            padding: 2px 6px;
            border-radius: 4px;
        }
        
        .file-actions {
            display: flex;
            gap: 10px;
        }
        
        .action-btn {
            padding: 8px 16px;
            background: #000;
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .action-btn:hover {
            background: #222;
            transform: translateY(-2px);
        }
        
        /* ================= 搜索结果 ================= */
        .search-result {
            background: #f9f9f9;
            border-radius: 12px;
            padding: 20px;
            margin-top: 20px;
        }
        
        .result-title {
            font-size: 20px;
            font-weight: 600;
            margin-bottom: 10px;
            color: #333;
        }
        
        .result-meta {
            margin-bottom: 15px;
            color: #666;
        }
        
        /* ================= 响应式设计 ================= */
        @media (max-width: 768px) {
            .main-buttons {
                grid-template-columns: 1fr;
            }
            
            .btn-group {
                flex-direction: column;
            }
            
            .file-item {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }
            
            .file-actions {
                width: 100%;
                justify-content: flex-end;
            }
        }
    </style>
</head>
<body>
    <!-- 白色顶部栏 -->
    <div class="top-bar">
        <button class="back-btn" onclick="history.back()">
            <i class="fas fa-arrow-left"></i>
        </button>
        <div class="page-title">JIIL文件管理系统</div>
    </div>
    
    <div class="container">
        <!-- 主功能按钮 -->
        <div class="main-buttons">
            <button class="big-button" onclick="showModal('upload')">
                <i class="fas fa-cloud-upload-alt"></i> 上传文件
            </button>
            <button class="big-button" onclick="showModal('search')">
                <i class="fas fa-search"></i> 文件查询
            </button>
            <button class="big-button" onclick="showModal('myfiles')">
                <i class="fas fa-folder"></i> 我的文件
            </button>
        </div>
        
        <!-- 系统提示 -->
        <div style="background: #f0f5ff; border-radius: 12px; padding: 20px; margin-bottom: 30px;">
            <h3 style="margin-bottom: 10px; color: #2563eb;">使用提示</h3>
            <p style="color: #666; line-height: 1.6;">
                每个用户最多可上传5个文件，文件有效期为24小时。
                上传文件后请记录文件ID，用于后续查询和下载。
            </p>
        </div>

        <!-- 上传弹窗 -->
        <div class="modal-overlay" id="uploadOverlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title">上传文件</h2>
                    <button class="close-btn" onclick="hideModals()">&times;</button>
                </div>
                
                <form id="uploadForm" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="upload">
                    
                    <div class="form-group">
                        <label class="form-label">文件名称</label>
                        <input type="text" id="fileName" name="name" class="form-input" placeholder="输入文件名称" required>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">选择文件</label>
                        <input type="file" id="fileInput" name="file" class="form-input" required>
                    </div>
                    
                    <div class="progress-bar">
                        <div class="progress-fill" id="progressFill"></div>
                    </div>
                    
                    <div class="btn-group">
                        <button type="button" class="btn btn-primary" onclick="startUpload()">
                            <i class="fas fa-upload"></i> 开始上传
                        </button>
                        <button type="button" class="btn btn-secondary" onclick="hideModals()">
                            <i class="fas fa-times"></i> 取消
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <!-- 查询弹窗 -->
        <div class="modal-overlay" id="searchOverlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title">文件查询</h2>
                    <button class="close-btn" onclick="hideModals()">&times;</button>
                </div>
                
                <div class="form-group">
                    <label class="form-label">输入文件ID</label>
                    <input type="text" id="searchInput" class="form-input" placeholder="输入6位文件ID">
                </div>
                
                <button class="btn btn-primary" onclick="doSearch()">
                    <i class="fas fa-search"></i> 立即查询
                </button>
                
                <div id="searchResult" class="search-result"></div>
            </div>
        </div>

        <!-- 我的文件弹窗 -->
        <div class="modal-overlay" id="myfilesOverlay">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title">我的文件</h2>
                    <button class="close-btn" onclick="hideModals()">&times;</button>
                </div>
                
                <div class="file-list-container" id="myFilesList">
                    <p style="text-align: center; padding: 20px; color: #666;">加载中...</p>
                </div>
            </div>
        </div>
    </div>

    <!-- 底部退出按钮 -->


    <script>
        // ================= 功能逻辑 =================
        let currentModal = null;
        let modalOpen = false;

        function showModal(type) {
            if (modalOpen) return; // 防止重复打开
            
            hideModals();
            currentModal = document.getElementById(type + 'Overlay');
            if (currentModal) {
                currentModal.style.display = 'flex';
                modalOpen = true;
                
                // 如果是我的文件弹窗，则加载内容
                if (type === 'myfiles') {
                    loadMyFiles();
                }
            }
        }

        function hideModals() {
            document.querySelectorAll('.modal-overlay').forEach(m => {
                m.style.display = 'none';
            });
            modalOpen = false;
        }

        function startUpload() {
            const form = document.getElementById('uploadForm');
            const formData = new FormData(form);
            const progressFill = document.getElementById('progressFill');
            
            const xhr = new XMLHttpRequest();
            
            // 设置上传进度监听
            xhr.upload.addEventListener('progress', function(e) {
                if (e.lengthComputable) {
                    const percent = (e.loaded / e.total) * 100;
                    progressFill.style.width = percent + '%';
                }
            });
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status === 200) {
                        try {
                            const response = JSON.parse(xhr.responseText);
                            if (response.status === 'success') {
                                alert(`上传成功！ID: ${response.data.id}`);
                                hideModals();
                            } else {
                                throw new Error(response.message || "上传失败");
                            }
                        } catch (e) {
                            alert('上传失败: ' + e.message);
                        }
                    } else {
                        alert('上传失败: 服务器错误');
                    }
                    // 重置进度条
                    progressFill.style.width = '0%';
                }
            };
            
            xhr.open('POST', '', true);
            xhr.send(formData);
        }

        async function doSearch() {
            const fileId = document.getElementById('searchInput').value.replace(/[^a-f0-9]/gi, '').substring(0,6);
            if (fileId.length !== 6) {
                alert('请输入6位有效文件ID');
                return;
            }

            try {
                const formData = new FormData();
                formData.append('action', 'search');
                formData.append('id', fileId);
                
                const response = await fetch('', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                if (result.status !== 'success') throw new Error(result.message);
                
                const div = document.getElementById('searchResult');
                div.innerHTML = `
                    <div class="result-title">${result.data.name}${result.data.extension ? '.'+result.data.extension : ''}</div>
                    <div class="result-meta">
                        <p>文件ID: <span class="file-id">${result.data.id}</span></p>
                        <p>文件大小: ${formatSize(result.data.size)}</p>
                        <p>过期时间: ${result.data.expire}</p>
                    </div>
                    <button class="btn btn-primary" onclick="downloadFile('${result.data.id}')">
                        <i class="fas fa-download"></i> 下载文件
                    </button>
                `;
            } catch (e) {
                alert('查询失败：' + e.message);
            }
        }

        async function loadMyFiles() {
            try {
                const container = document.getElementById('myFilesList');
                container.innerHTML = '<p style="text-align: center; padding: 20px; color: #666;">加载中...</p>';
                
                const response = await fetch('', {
                    method: 'POST',
                    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                    body: 'action=myfiles'
                });
                
                if (!response.ok) throw new Error('网络错误');
                const result = await response.json();
                
                if (result.status !== 'success') throw new Error(result.message);
                
                container.innerHTML = '';
                
                if (result.data.length === 0) {
                    container.innerHTML = '<p style="text-align: center; padding: 30px; color: #666;">暂无文件</p>';
                } else {
                    result.data.forEach(file => {
                        const fileItem = document.createElement('div');
                        fileItem.className = 'file-item';
                        fileItem.innerHTML = `
                            <div class="file-info">
                                <div class="file-name">${file.name}</div>
                                <div class="file-meta">
                                    <span>ID: <span class="file-id">${file.id}</span></span>
                                    <span>大小: ${formatSize(file.size)}</span>
                                    <span>上传: ${file.upload_time}</span>
                                </div>
                            </div>
                            <div class="file-actions">
                                <button class="action-btn" onclick="downloadFile('${file.id}')">
                                    <i class="fas fa-download"></i> 下载
                                </button>
                            </div>
                        `;
                        container.appendChild(fileItem);
                    });
                }
            } catch (e) {
                alert('加载失败: ' + e.message);
                console.error(e);
            }
        }

        function downloadFile(fileId) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `
                <input type="hidden" name="action" value="download">
                <input type="hidden" name="id" value="${fileId}">
            `;
            document.body.appendChild(form);
            form.submit();
        }

        function formatSize(bytes) {
            const units = ['B', 'KB', 'MB', 'GB'];
            let size = bytes;
            let unit = 0;
            while (size >= 1024 && unit < units.length - 1) {
                size /= 1024;
                unit++;
            }
            return `${size.toFixed(2)} ${units[unit]}`;
        }
    </script>
</body>
</html>